package com.zfl.thread.day03;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Data
@AllArgsConstructor
@NoArgsConstructor
class Car {

    public static Lock LOCK = new ReentrantLock();
    public static Condition CON_PRODUCT = LOCK.newCondition();
    public static Condition CON_CONSUMER = LOCK.newCondition();
    public static boolean FLAG = true;
    private String name;


}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ProductThread implements Runnable {

    private Car car;

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            Car.LOCK.lock();
            try {
                while (!Car.FLAG) {
                    Car.CON_PRODUCT.await();
                }
                car.setName((char) ('A' + i) + "");
                System.out.println(Thread.currentThread().getName() + "生产了" + car.getName());
                Car.FLAG = !Car.FLAG;
                Car.CON_CONSUMER.signalAll();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                Car.LOCK.unlock();
            }
        }
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ConsumerThread implements Runnable {

    private Car car;

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            Car.LOCK.lock();
            try {
                while (Car.FLAG) {
                    Car.CON_CONSUMER.await();
                }
                System.out.println(Thread.currentThread().getName() + "消费了" + car.getName());
                Car.FLAG = !Car.FLAG;
                Car.CON_PRODUCT.signalAll();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                Car.LOCK.unlock();
            }
        }
    }
}

public class ProductConsumer {
    public static void main(String[] args) {
        Car car = new Car();
        new Thread(new ProductThread(car),"厂商").start();
        new Thread(new ConsumerThread(car),"商家").start();
    }
}
